"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 故障&可靠性测试
Case Name   : 主机表空间级联目录权限不同，表空间内表插入、查询数据及删除表操作
Create At   : 2022/05/16
Owner       : @peilinqian
Description :
    1、创建表空间;
    2、创建表;
    3、修改表空间目录权限为000，进行表数据插入、查询、删除表操作;
    4、恢复集群，创建表;
    5、修改表空间目录权限为100;进行表数据插入、查询、删除表操作;
    6、恢复集群，创建表;
    7、修改表空间目录权限为200，进行表数据插入、查询、删除表操作;
    8、恢复集群，创建表;
    9、修改表空间目录权限为300，进行表数据插入、查询、删除表操作;
    10、恢复集群，创建表;
    11、修改表空间目录权限为400，进行表数据插入、查询、删除表操作;
    12、恢复集群，创建表;
    13、修改表空间目录权限为500，进行表数据插入、查询、删除表操作;
    14、恢复集群，创建表;
    15、修改表空间目录权限为600，进行表数据插入、查询、删除表操作;
    16、恢复集群，创建表;
Expect      :
    1、创建表空间;创建成功
    2、创建表;创建成功
    3、修改表空间目录权限为000，进行表数据插入、查询、删除表操作;操作失败；删除表数据库panic stop
    4、恢复集群，创建表; 成功
    5、修改表空间目录权限为100;进行表数据插入、查询、删除表操作;插入查询操作失败，删除成功但是提示warning，数据库正常
    6、恢复集群，创建表; 成功
    7、修改表空间目录权限为200，进行表数据插入、查询、删除表操作;操作失败；删除表数据库panic stop
    8、恢复集群，创建表; 成功
    9、修改表空间目录权限为300，进行表数据插入、查询、删除表操作;插入查询操作失败，删除成功但是提示warning，数据库正常
    10、恢复集群，创建表; 成功
    11、修改表空间目录权限为400，进行表数据插入、查询、删除表操作;操作失败；删除表数据库panic stop
    12、恢复集群，创建表; 成功
    13、修改表空间目录权限为500，进行表数据插入、查询、删除表操作;插入查询操作失败，删除成功但是提示warning，数据库正常
    14、恢复集群，创建表; 成功
    15、修改表空间目录权限为600，进行表数据插入、查询、删除表操作;操作失败；删除表数据库panic stop
    16、恢复集群，创建表; 成功
History     :
"""

import os
import re
import unittest

from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.CommonSH import RestartDbCluster
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro


class DbSysCase278(unittest.TestCase):
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.pri_root = Node(node='PrimaryRoot')
        self.pri_dbuser = Node(node='PrimaryDbUser')
        self.sta1_dbuser = Node(node='Standby1DbUser')
        self.sta2_dbuser = Node(node='Standby2DbUser')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.constant = Constant()
        self.com = Common()
        self.tbspc_name = 'tbspc_dbsys278'
        self.tbspc_path = os.path.join(os.path.dirname(
            macro.DB_INSTANCE_PATH), 'tbspc_dbsys278')
        self.create_ts_sql = f"create tablespace {self.tbspc_name} " \
            f"location '{self.tbspc_path}';"
        self.drop_ts_sql = f"drop tablespace if exists {self.tbspc_name};"
        self.tb_name = 't_dbsys278'
        self.create_tb_sql = f"drop table if exists {self.tb_name};" \
            f"create table {self.tb_name} (id int,name varchar(100)) " \
            f"tablespace {self.tbspc_name};"
        self.insert_num = 100000
        self.insert_sql = f"insert into {self.tb_name} " \
            f"select generate_series(1, {self.insert_num})," \
            f"'name-'||generate_series(1, {self.insert_num});" \
            f"checkpoint;"
        self.select_sql = f"select count(*) from {self.tb_name};"
        self.drop_tb_sql = f"drop table if exists {self.tb_name};checkpoint;"
        self.file_location = ''
        self.err_msg = 'ERROR:  could not open file .*: Permission denied'
        self.err_msg1 = 'PANIC:  could not stat file .*: Permission denied'
        self.err_msg2 = 'WARNING:  could not truncate file .*: ' \
                        'Permission denied'
        self.chmod_cmd = f'chmod -R authority {self.tbspc_path} &&' \
            f'ls -al {os.path.dirname(self.tbspc_path)} ' \
            f'|grep {self.tbspc_name}'

    def test_main(self):
        step_txt = '----step1:创建表空间;expect:创建成功----'
        self.log.info(step_txt)
        create_result = self.pri_sh.executDbSql(self.create_ts_sql)
        self.log.info(create_result)
        self.assertIn(self.constant.CREATE_TBLSPACE_SUCCESS_MSG,
                      create_result, "执行失败" + step_txt)

        step_txt = '----step2:创建表;expect:创建成功----'
        self.log.info(step_txt)
        create_result = self.pri_sh.executDbSql(self.create_tb_sql)
        self.log.info(create_result)
        self.assertIn(self.constant.TABLE_CREATE_SUCCESS, create_result,
                      "执行失败" + step_txt)

        step_txt = '----查询表实际路径----'
        self.log.info(step_txt)
        location_sql = f"select pg_relation_filepath(" \
            f"(select oid from pg_class where relname = '{self.tb_name}')" \
            f"::regclass);"
        tmp = self.pri_sh.executDbSql(location_sql)
        t_link = tmp.splitlines()[-2].strip()
        self.log.info('数据库对象文件链接路径：' + t_link)
        t_link_dir = os.path.dirname(
            os.path.join(macro.DB_INSTANCE_PATH, t_link))
        ls_cmd = f'cd $(readlink -f {t_link_dir}) && pwd'
        self.log.info(ls_cmd)
        self.file_location = self.pri_root.sh(ls_cmd).result()
        self.log.info('--数据库对象文件所在的路径--')
        self.log.info(self.file_location)

        step_txt = '----step3:修改表空间目录权限为000，进行表数据插入、查询、删除表操作;' \
                   'expect:操作失败；删除表数据库panic stop----'
        self.log.info(step_txt)
        chmod_cmd = self.chmod_cmd.replace('authority', '000')
        chmod_result = self.com.get_sh_result(self.pri_root, chmod_cmd)
        self.assertIn('d---------', chmod_result, "执行失败" + step_txt)
        check_result = self.check_op()
        self.assertEqual(len(re.findall(self.err_msg, check_result[0])), 1,
                         "执行失败" + step_txt)
        self.assertEqual(len(re.findall(self.err_msg, check_result[1])), 1,
                         "执行失败" + step_txt)
        self.assertEqual(len(re.findall(self.err_msg1, check_result[2])), 2,
                         "执行失败" + step_txt)
        status = self.pri_sh.getDbClusterStatus('status')
        self.assertFalse(status, "执行失败" + step_txt)

        step_txt = '----step4:恢复集群，创建表; expect:成功----'
        self.log.info(step_txt)
        recovery_msg = self.recovery()
        self.assertTrue(recovery_msg, "执行失败" + step_txt)

        step_txt = '----step5:修改表空间目录权限为100;进行表数据插入、查询、删除表操作;' \
                   'expect:插入查询操作失败，删除成功但是提示warning，数据库正常----'
        self.log.info(step_txt)
        chmod_cmd = self.chmod_cmd.replace('authority', '100')
        chmod_result = self.com.get_sh_result(self.pri_root, chmod_cmd)
        self.assertIn('d--x------', chmod_result, "执行失败" + step_txt)
        check_result = self.check_op()
        self.assertEqual(len(re.findall(self.err_msg, check_result[0])), 1,
                         "执行失败" + step_txt)
        self.assertEqual(len(re.findall(self.err_msg, check_result[1])), 1,
                         "执行失败" + step_txt)
        self.assertEqual(len(re.findall(self.err_msg2, check_result[2])), 1,
                         "执行失败" + step_txt)
        status = self.pri_sh.getDbClusterStatus('status')
        self.assertTrue(status, "执行失败" + step_txt)

        step_txt = '----step6:恢复集群，创建表; expect:成功----'
        self.log.info(step_txt)
        recovery_msg = self.recovery()
        self.assertTrue(recovery_msg, "执行失败" + step_txt)

        step_txt = '----step7:修改表空间目录权限为200，进行表数据插入、查询、删除表操作;' \
                   'expect:操作失败；删除表数据库panic stop----'
        self.log.info(step_txt)
        chmod_cmd = self.chmod_cmd.replace('authority', '200')
        chmod_result = self.com.get_sh_result(self.pri_root, chmod_cmd)
        self.assertIn('d-w-------', chmod_result, "执行失败" + step_txt)
        check_result = self.check_op()
        self.assertEqual(len(re.findall(self.err_msg, check_result[0])), 1,
                         "执行失败" + step_txt)
        self.assertEqual(len(re.findall(self.err_msg, check_result[1])), 1,
                         "执行失败" + step_txt)
        self.assertEqual(len(re.findall(self.err_msg1, check_result[2])), 2,
                         "执行失败" + step_txt)
        status = self.pri_sh.getDbClusterStatus('status')
        self.assertFalse(status, "执行失败" + step_txt)

        step_txt = '----step8:恢复集群，创建表; expect:成功----'
        self.log.info(step_txt)
        recovery_msg = self.recovery()
        self.assertTrue(recovery_msg, "执行失败" + step_txt)

        step_txt = '----step9:修改表空间目录权限为300，进行表数据插入、查询、删除表操作;' \
                   'expect:插入查询操作失败，删除成功但是提示warning，数据库正常----'
        self.log.info(step_txt)
        chmod_cmd = self.chmod_cmd.replace('authority', '300')
        chmod_result = self.com.get_sh_result(self.pri_root, chmod_cmd)
        self.assertIn('d-wx------', chmod_result, "执行失败" + step_txt)
        check_result = self.check_op()
        self.assertEqual(len(re.findall(self.err_msg, check_result[0])), 1,
                         "执行失败" + step_txt)
        self.assertEqual(len(re.findall(self.err_msg, check_result[1])), 1,
                         "执行失败" + step_txt)
        self.assertEqual(len(re.findall(self.err_msg2, check_result[2])), 1,
                         "执行失败" + step_txt)
        status = self.pri_sh.getDbClusterStatus('status')
        self.assertTrue(status, "执行失败" + step_txt)

        step_txt = '----step10:恢复集群，创建表; expect:成功----'
        self.log.info(step_txt)
        recovery_msg = self.recovery()
        self.assertTrue(recovery_msg, "执行失败" + step_txt)

        step_txt = '----step11:修改表空间目录权限为400，进行表数据插入、查询、删除表操作;' \
                   'expect:操作失败；删除表数据库panic stop----'
        self.log.info(step_txt)
        chmod_cmd = self.chmod_cmd.replace('authority', '400')
        chmod_result = self.com.get_sh_result(self.pri_root, chmod_cmd)
        self.assertIn('dr--------', chmod_result, "执行失败" + step_txt)
        check_result = self.check_op()
        self.assertEqual(len(re.findall(self.err_msg, check_result[0])), 1,
                         "执行失败" + step_txt)
        self.assertEqual(len(re.findall(self.err_msg, check_result[1])), 1,
                         "执行失败" + step_txt)
        self.assertEqual(len(re.findall(self.err_msg1, check_result[2])), 2,
                         "执行失败" + step_txt)
        status = self.pri_sh.getDbClusterStatus('status')
        self.assertFalse(status, "执行失败" + step_txt)

        step_txt = '----step12:恢复集群，创建表; expect:成功----'
        self.log.info(step_txt)
        recovery_msg = self.recovery()
        self.assertTrue(recovery_msg, "执行失败" + step_txt)

        step_txt = '----step13:修改表空间目录权限为500，进行表数据插入、查询、删除表操作;' \
                   'expect:插入查询操作失败，删除成功但是提示warning，数据库正常----'
        self.log.info(step_txt)
        chmod_cmd = self.chmod_cmd.replace('authority', '500')
        chmod_result = self.com.get_sh_result(self.pri_root, chmod_cmd)
        self.assertIn('dr-x------', chmod_result, "执行失败" + step_txt)
        check_result = self.check_op()
        self.assertEqual(len(re.findall(self.err_msg, check_result[0])), 1,
                         "执行失败" + step_txt)
        self.assertEqual(len(re.findall(self.err_msg, check_result[1])), 1,
                         "执行失败" + step_txt)
        self.assertEqual(len(re.findall(self.err_msg2, check_result[2])), 1,
                         "执行失败" + step_txt)
        status = self.pri_sh.getDbClusterStatus('status')
        self.assertTrue(status, "执行失败" + step_txt)

        step_txt = '----step14:恢复集群，创建表; expect:成功----'
        self.log.info(step_txt)
        recovery_msg = self.recovery()
        self.assertTrue(recovery_msg, "执行失败" + step_txt)

        step_txt = '----step15:修改表空间目录权限为600，进行表数据插入、查询、删除表操作;' \
                   'expect:操作失败；删除表数据库panic stop----'
        self.log.info(step_txt)
        chmod_cmd = self.chmod_cmd.replace('authority', '600')
        chmod_result = self.com.get_sh_result(self.pri_root, chmod_cmd)
        self.assertIn('drw-------', chmod_result, "执行失败" + step_txt)
        check_result = self.check_op()
        self.assertEqual(len(re.findall(self.err_msg, check_result[0])), 1,
                         "执行失败" + step_txt)
        self.assertEqual(len(re.findall(self.err_msg, check_result[1])), 1,
                         "执行失败" + step_txt)
        self.assertEqual(len(re.findall(self.err_msg1, check_result[2])), 2,
                         "执行失败" + step_txt)
        status = self.pri_sh.getDbClusterStatus('status')
        self.assertFalse(status, "执行失败" + step_txt)

        step_txt = '----step16:恢复集群，创建表; expect:成功----'
        self.log.info(step_txt)
        recovery_msg = self.recovery()
        self.assertTrue(recovery_msg, "执行失败" + step_txt)

    def check_op(self):
        """
        :return: 数据插入、查询、删除表执行结果
        """
        insert_result = self.pri_sh.executDbSql(self.insert_sql)
        self.log.info(insert_result)
        select_result = self.pri_sh.executDbSql(self.select_sql)
        self.log.info(select_result)
        drop_result = self.pri_sh.executDbSql(self.drop_tb_sql)
        self.log.info(drop_result)
        return insert_result, select_result, drop_result

    def recovery(self):
        self.log.info("--恢复集群--")
        chmod_cmd = self.chmod_cmd.replace('authority', '700')
        self.com.get_sh_result(self.pri_root, chmod_cmd)
        start_result = self.pri_sh.startDbCluster()
        self.log.info("--创建表--")
        create_msg = self.pri_sh.executDbSql(self.create_tb_sql)
        self.log.info(create_msg)
        return start_result and \
               self.constant.TABLE_CREATE_SUCCESS in create_msg

    def tearDown(self):
        self.log.info("----this is tearDown----")
        step1_txt = '----清理残余表文件; expect:成功----'
        self.log.info(step1_txt)
        chmod_cmd = self.chmod_cmd.replace('authority', '700')
        chmod_result = self.com.get_sh_result(self.pri_root, chmod_cmd)
        drop_tb_result = self.pri_sh.executDbSql(self.drop_tb_sql)
        self.log.info(drop_tb_result)
        if self.file_location:
            rm_cmd = f"rm -rf {os.path.join(self.file_location, '')}*"
            self.log.info(rm_cmd)
            self.pri_dbuser.sh(rm_cmd).result()
        step2_txt = '----清理表空间; expect:成功----'
        self.log.info(step2_txt)
        drop_ts_result = self.pri_sh.executDbSql(self.drop_ts_sql)
        self.log.info(drop_ts_result)
        step3_txt = '----删除表空间路径; expect:成功----'
        self.log.info(step3_txt)
        del_cmd = f"rm -rf {self.tbspc_path}; " \
            f"if [ -d {self.tbspc_path} ]; then echo 'exists'; " \
            f"else echo 'not exists'; fi;"
        self.log.info(del_cmd)
        del_result1 = self.pri_dbuser.sh(del_cmd).result()
        del_result2 = self.sta1_dbuser.sh(del_cmd).result()
        del_result3 = self.sta2_dbuser.sh(del_cmd).result()
        self.log.info(del_result1)
        self.log.info(del_result2)
        self.log.info(del_result3)

        self.log.info(f'-----{os.path.basename(__file__)} end-----')
        self.assertIn('drwx------', chmod_result, "执行失败" + step1_txt)
        self.assertIn(self.constant.TABLE_DROP_SUCCESS, drop_tb_result,
                      "执行失败" + step1_txt)
        self.assertIn(self.constant.drop_tablespace_success_msg,
                      drop_ts_result, "执行失败" + step2_txt)
        self.assertEqual('not exists', del_result1, "执行失败" + step3_txt)
        self.assertEqual('not exists', del_result2, "执行失败" + step3_txt)
        self.assertEqual('not exists', del_result3, "执行失败" + step3_txt)
